package ryulib;

import android.util.Log;

public class ThreadRepeater implements Runnable {
	
	private Boolean _Active = false; 
	private Boolean _Pause = false; 
	private Thread _Thread = null;
	private long _OldTick;
	
	// Property
	private long _Interval = 0;
	
	// Event
	private OnRepeatListener _OnRepeat = null;

	public final void start() {
		_OldTick = System.currentTimeMillis();
		
		_Active = true;
		_Thread = new Thread(this);
		_Thread.start();
	}
	
	public final void pause() {
		_Pause = true;
	}
	
	public final void resume() {
		_Pause = false;
	}
	
	public final void sleep(long time) {
		try {
    		Thread.sleep(time);
		} catch (InterruptedException e) {
			Log.w("RyuLib", "ThreadRepeater.sleep() Exception.");
		}       		
	}
	
	public final void stop() {
        _Active = false;
        if (_Thread == null) return;
	}

	public final void termiate() {
        _Active = false;
        if (_Thread == null) return;
        
        Thread temp = _Thread;
        _Thread = null;

        boolean retry = true;
        while (retry) {
            try {
            	temp.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
	}	
	
	public final void run() {
		while (_Active) {
			long tick = System.currentTimeMillis();
			
			if ((_Pause == false) && (_OnRepeat != null)) {
				_OnRepeat.onRepeat(this, tick - _OldTick);
        		if (_Interval > 0) sleep(_Interval);
			} else {
				sleep(5);
			}
			
			_OldTick = tick;	
		}
		
        _Thread = null;
	}
	
	public final void setRepeatListener(OnRepeatListener value) {
		_OnRepeat = value;
	}

	public final OnRepeatListener getRepeatListener() {
		return _OnRepeat;
	}

	public final void setInterval(long value) {
		_Interval = value;
	}

	public final long getInterval() {
		return _Interval;
	}
	
}
